using System.Data;
using Admin2025.Domain.Entities.App;
using Admin2025.Domain.Repositories;
using Admin2025.Infrastructure.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace Admin2025.Infrastructure.Repositories;

public class FileRepository : Repository<AppFile>, IFileRepository
{
  private new readonly IDbConnection _db;
  private readonly IConfiguration _config;

  public FileRepository(Admin2025DbContext factory, IConfiguration config) : base(factory)
  {
    _db = factory.CreateConnection();
    _config = config;
  }

  public async Task<AppFile?> UploadFileAsync(IFormFile file, Guid userId)
  {
    var storageRootPath = _config["FileUpload:StorageRootPath"] ?? "wwwroot/uploads";
    var fileName = $"{Guid.NewGuid()}_{file.FileName}";
    var filePath = Path.Combine(storageRootPath, fileName);

    Directory.CreateDirectory(storageRootPath);

    using (var stream = new FileStream(filePath, FileMode.Create))
    {
      await file.CopyToAsync(stream);
    }

    var appFile = new AppFile
    {
      Id = Guid.NewGuid(),
      FileName = file.FileName,
      FilePath = filePath,
      FileSize = file.Length,
      ContentType = file.ContentType,
      UploadedAt = DateTime.UtcNow,
      UploadedBy = userId
    };

    await CreateAsync(appFile);
    return appFile;
  }
}